package com.security.securityandoauth.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 * 自定义认证失败处理器 -- 认证失败返回错误信息
 */

public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 封装数据
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code", -1);
        resultMap.put("message", "登录失败");
        String result = JSON.toJSONString(resultMap);

        // 输出响应结果
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(result);
    }
}
